package AdamsDevice;
import java.awt.List;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TCPSocketServer implements Runnable{

   /**
    * Accept this many connections.
    */
   private int my_backlog = 5;

   /**
    * The server socket.
    */
   private ServerSocket my_serverSocket;

   /**
    * Create the server socket.
    * @param a_port the port that the server socket should listen on.
    */
   public TCPSocketServer(int a_port) {
      try {
         my_serverSocket = new ServerSocket(a_port, my_backlog);
         System.out.println("TCP socket listening on port " + a_port);
      } catch (IOException ioe) {
         ioe.printStackTrace();
      } catch (SecurityException se) {
         se.printStackTrace();
      }
   }
   
   //thread that keeps listening

public void run() {
	  while (true) {
	         try {
	        	String ACK = "";
	            // Listens for a connection to be made to this socket.
	            Socket socket = my_serverSocket.accept();

	            // Wrap a buffered reader round the socket input stream.
	            BufferedReader in = new BufferedReader(new InputStreamReader(socket
	                  .getInputStream()));

	            // Read in the message
	            String msg = in.readLine(); 

	            // Print the message to the console
	            System.out.println("message recieved: "+msg);
	            
	            //begin to reply to the port.
	            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);           
	            out.println("thanks for:" +msg);
	           
	            
	            // tidy up
	            in.close();
	            socket.close();
	         } catch (IOException ioe) {
	            ioe.printStackTrace();
	         } catch (SecurityException se) {
	            se.printStackTrace();
	         }
	      }
	   }
} // end class

